//
//  MeVC.swift
//  AliBaiChuan
//
//  Created by 郑东喜 on 2017/2/21.
//  Copyright © 2017年 郑东喜. All rights reserved.
//  我的

import UIKit

class MeVC: UIViewController {
    
    //会话session
    fileprivate lazy var _alSession : ALBBSession = {
        let _se : ALBBSession = ALBBSession()
        return _se
    }()
    
    //name 
    var name : String? {
        
        didSet {
            self.tableView.reloadData()
        }
    }
    
    //imgUrl
    var imgUrl : String?
    
    ///用户信息
    fileprivate lazy var _session : ALBBSDK = {
        let _se : ALBBSDK = ALBBSDK()
        return _se
    }()
    
    //登陆状态
    fileprivate var statusStr : String?
    
    //数据源
    lazy var dataSource: NSMutableArray = {
        let ns : NSMutableArray = ["订单","设置",""]
        
        
        return ns
    }()
    
    lazy var headerView: MyHeaderView = {
        let cc : MyHeaderView = MyHeaderView()
        cc.frame = CGRect.init(x: 0, y: 0, width: SW, height: 100)
        return cc
    }()
    
    ///表格
    lazy var tableView: UITableView = {
        let t : UITableView = UITableView.init(frame: self.view.bounds)
        
        t.delegate = self
        t.dataSource = self
        return t
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        //给定默认值
        name = ""
        
        imgUrl =  "https://www.google.com.hk/images/branding/googlelogo/2x/googlelogo_color_120x44dp.png"
        
        self.title = "我的"
        
        
    
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        setUI()
    }

}

// MARK:- 设置视图
extension MeVC {
    func setUI() -> Void {
        
        //获取淘宝用户信息
        getUserInfo()
        
        tableView.tableHeaderView = headerView
        view.addSubview(tableView)
    }
}

// MARK:- UITableViewDelegate
extension MeVC : UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cellID") as? TCell
        
        if cell == nil {
            cell = TCell.init(style: .default, reuseIdentifier: "cellID")
        }

        cell?.textTF.isUserInteractionEnabled = false
        cell?.textTF.text = self.dataSource[indexPath.row] as? String
        cell?.textTF.font = UIFont.init(name: "Sketch 3D", size: 14)
        cell?.delegate = self
        cell?.index = indexPath as NSIndexPath?
        
    
        switch indexPath.row {
            ///淘宝授权登陆状态
        case 1:
            cell?.textTF.text = "登陆状态 : " + self.getStatus()
            break
            //淘宝授权信息
        case 2:
            cell?.textTF.text = "淘宝用户信息 : " + self.name!
            
//            let request : URLRequest = URLRequest.init(url: URL.init(string: self.imgUrl!)!)
//
////            NSURLConnection.sendAsynchronousRequest(request, queue: .main, completionHandler: { (_, data, error) in
////                cell?.imgView.image = UIImage.init(data: data!)
////            })
        
            break
        default:
            break
        }
        return cell!
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch indexPath.row {
            ///订单
        case 0:
            self.hidesBottomBarWhenPushed = true
            
            self.showSelectIndex()
            
            self.hidesBottomBarWhenPushed = false
            break
        case 1:
            self.logout()
            break
            
        case 2:
            
            break
        default:
            break
        }
    }
}

// MARK:- 表格代理
extension MeVC : TCellDelagate {
    func getText(str: String, cellIndex index: NSIndexPath) {
        
    }
}

// MARK:- 获取登陆状态
extension MeVC {
    // MARK:- 获取登陆状态
    fileprivate func getStatus() -> String {
        if _alSession.isLogin() == true {
            self.statusStr = "已登陆"
            return self.statusStr!
        } else {
            self.statusStr = "未登陆"
            
            return self.statusStr!
        }
    }
    
    ///显示订单类型
    fileprivate func showSelectIndex()-> Void {
        ///提示框显示结果
        let alertVc = UIAlertController.init(title: "提示", message: "选择订单类型", preferredStyle: .actionSheet)
        
        alertVc.addAction(UIAlertAction.init(title: "全部订单", style: .default, handler: { (alert) in
            self.mydetailOrders(iiitn: Int("0")!)
        }))
        
        alertVc.addAction(UIAlertAction.init(title: "待付款订单", style: .default, handler: { (alert) in
            self.mydetailOrders(iiitn: Int("1")!)
        }))
        alertVc.addAction(UIAlertAction.init(title: "待发货订单", style: .default, handler: { (alert) in
            self.mydetailOrders(iiitn: Int("2")!)
        }))
        alertVc.addAction(UIAlertAction.init(title: "待收货订单", style: .default, handler: { (alert) in
            self.mydetailOrders(iiitn: Int("3")!)
        }))
        alertVc.addAction(UIAlertAction.init(title: "待评价订单", style: .default, handler: { (alert) in
            self.mydetailOrders(iiitn: Int("4")!)
        }))
        
        alertVc.addAction(UIAlertAction.init(title: "确定", style: .default, handler: nil))
        
        self.present(alertVc, animated: true, completion: nil)
    }
    
    /**
     * 创建我的订单列表页面
     *
     * @param status 所要展示订单的订单状态
     *  0: 为全部订单
     *  1: 为待付款订单
     *  2: 为待发货订单
     *  3: 为待收货订单
     *  4: 为待评价订单
     * @param isAllOrder  是否显示全部订单
     *
     *  YES: 显示全部订单
     *  NO : 显示ISV自己创建的订单
     *
     * @return 我的订单列表页面
     */
    // MARK:- 我的订单
    fileprivate func mydetailOrders(iiitn : Int) -> Void {
        let page = AlibcTradePageFactory.myOrdersPage(iiitn, isAllOrder: true)
        let service = AlibcTradeSDK.sharedInstance().tradeService()
        
        let showParams : AlibcTradeShowParams = AlibcTradeShowParams()
        showParams.openType = .H5
        showParams.isNeedPush = true
        
        service?.show(showParams.isNeedPush ? self.navigationController! : self,
                      page: page,
                      showParams:showParams,
                      
                      taoKeParams: nil,
                      trackParam: ["track_key":"track_value"],
                      tradeProcessSuccessCallback: { (result) in
                        print("\((#file as NSString).lastPathComponent):(\(#line))",result as Any)
                        
        }, tradeProcessFailedCallback: { (error) in
            
        })
    }
}

// MARK:- 获取用户头像、名字
extension MeVC {
    fileprivate func getUserInfo() -> Void {
        if localSave.object(forKey: "loginStatus") != nil{
            let arr = localSave.object(forKey: "loginStatus") as? NSMutableArray
            
            self.name = arr?[0] as? String
        } else {
            self.name = ""
        }
    }
}


// MARK:- 是否退出登陆
extension MeVC {
    // MARK:- 用户退出
    fileprivate func logout() -> Void {
        _session.logout()
        
        print("\((#file as NSString).lastPathComponent):(\(#line))",_alSession.isLogin())
        ///1.检查登陆状态
        if _alSession.isLogin() == true {
            showWithAlert(data: "退出成功")
            
            localSave.removeObject(forKey: "loginStatus")
            localSave.synchronize()
        } else {
            showWithAlert(data: "未登陆")
            
            localSave.removeObject(forKey: "loginStatus")
            localSave.synchronize()
        }
        
        self.tableView.reloadData()
    }
}
